<?php

namespace Acme\ContestBundle\Controller;

use Acme\ContestBundle\Form\CtInfoType;

use Acme\ContestBundle\Form\ContestCreateType;

use Acme\ContestBundle\Entity\CtInfo;

use Acme\ContestBundle\Form\ContestManageType;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;

use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Response;

/**
 * @Route("/backend/contest/manage")
 */
class ContestCRUDController extends Controller
{
    /**
     * @Route("", name="AcmeContestBundle_ContestSearch")
     * @Template()
     */
    public function indexAction() {
    	$buildOption['role'] = $this->get('security.context')->getToken()->getUser()->getRoles();
    	$form = $this->createForm(new ContestManageType(), '', $buildOption);
        return array('form' => $form->createView());
    }
    
    /**
     * @Route("/create", name="AcmeContestBundle_ContestCreate")
     * @Template()
     */
    public function createAction() {
    	$contest = new CtInfo();
    	$buildOption['role'] = $this->get('security.context')->getToken()->getUser()->getRoles();
    	$form = $this->createForm(new ContestCreateType(), $contest, $buildOption);
    	return array('form' => $form->createView());
    }
    
    /**
     * @Route("/list", name="AcmeContestBundle_ContestList")
     * @Template()
     */
    public function listAction() {
    	$request = $this->get('request');
    	if ($request->isXmlHttpRequest()) {
    		$condition = $request->get('contest_manage');
    		
    		if ($this->get('security.context')->isGranted('ROLE_UNIVERSITY_ADMIN')) {
    			$condition['university'] =
    			$this->get('security.context')->getToken()
    			->getUser()->getUserInfo()->getUniversity();
    		}
    		
    		$em = $this->getDoctrine()->getEntityManager();
    		$contest = $em->getRepository('AcmeContestBundle:CtInfo')->findCtByConditionJoined($condition);
    		
    		return array('contests' => $contest);
    	}
    	throw $this->createNotFoundException();
    }
    
    /**
     * @Route("/info", name="AcmeContestBundle_ContestInfo")
     * @Template()
     * TODO
     */
    public function infoAction() {
    	$request = $this->get('request');
    	 
    	$userInfo = new CmUserInfo();  // The form should be created by Owning Side
    	 
    	$buildOption['build_for'] = 'edit';
    	$form = $this->createForm(new UserInfoType(), $userInfo, $buildOption);
    	 
    	return array("form" => $form->createView());
    }
    
    /**
     * @Route("/verify", name="AcmeContestBundle_ContestVerify")
     * @Template()
     * TODO
     */
    public function verifyAction() {
    	$request = $this->get('request');
    	if ($request->isXmlHttpRequest()) {
    		$condition['id'] = $request->get('id');
    		$result = $request->get('result');
    
    		if ($this->get('security.context')->isGranted('ROLE_UNIVERSITY_ADMIN')) {
    			$condition['university'] =
    			$this->get('security.context')->getToken()
    			->getUser()->getUserInfo()->getUniversity();
    		}
    
    		$em = $this->getDoctrine()->getEntityManager();
    		$user = $em->getRepository('AcmeUserBundle:CmUser')->findUserByConditionJoined($condition);
    
    		if (!$user) {
    			throw $this->createNotFoundException('No user found for id ' . $condition['id']);
    		}
    
    		$userStatusEn = $this->container->getParameter('userStatusEn');
    		if ($userStatusEn[$user->getUserStatus()] == 'to-verify') {
    			$user->setUserStatus(array_search($result, $this->container->getParameter('userStatusEn')));
    			$em->flush();
    			return new Response('success');
    		}
    	}
    	throw $this->createNotFoundException();
    }
    
    /**
     * @Route("/edit", name="AcmeContestBundle_ContestEdit")
     * @Template()
     * TODO
     */
    public function editAction() {
    	$request = $this->get('request');
    	if ($request->isXmlHttpRequest()) {
    		
    		if ($request->get('id')) {
    			$condition['id'] = $request->get('id');
    			
    			if ($this->get('security.context')->isGranted('ROLE_UNIVERSITY_ADMIN')) {
    				$condition['university'] =
	    				$this->get('security.context')->getToken()
	    				->getUser()->getUserInfo()->getUniversity();
    			}
    			
    			if ($request->get('show_modal_request')) {
    				$em = $this->getDoctrine()->getEntityManager();
    				$contest = $em->getRepository('AcmeContestBundle:CtInfo')->findCtByConditionJoined($condition);
    				//echo "<pre>";
    				//print_r($contest);
    				//return ;
    				if (!$contest) {
    					throw $this->createNotFoundException('No contest found for id ' . $condition['id']);
    				}
    
    				$contestInfo = new CtInfo();  // The form should be created by Owning Side
    				
    				$buildOption['role'] = $this->get('security.context')->getToken()->getUser()->getRoles();
    				$buildOption['build_for'] = 'edit';
    				$form = $this->createForm(new CtInfoType(), $contestInfo, $buildOption);
    				
    				return array('form' => $form->createView(), 'contest' => $contest);
    			} else {
    				/**
    				 * TODO flush posts
    				 */
    				return new Response('success');
    			}
    		} else {  // create new contest
    			$form_data = $request->get('contest_create');
    			
    			$em = $this->getDoctrine()->getEntityManager();
    			$contest = new CtInfo();
    			
    			$contestTypeInfo = $em->getRepository('AcmeCommonBundle:ConstContestType')
    				->find($form_data['contestType']);
    			
    			if (!$contestTypeInfo) {
    				throw $this->createNotFoundException('No contest type found for id');
    			}
    			
    			$condition['id'] = $form_data['applyBy'];
    			
    			if ($this->get('security.context')->isGranted('ROLE_SUPER_ADMIN')) {
    				$condition['university'] = $form_data['university'];
    			} else {
    				$condition['university'] = $this->get('security.context')->getToken()->getUser()->getUserInfo()->getUniversity();
    			}
    			
    			$condition['userCategory'] = array_search('teacher', $this->container->getParameter('userCategoryEn'));
    			$condition['userStatus'] = array_search('success-verify', $this->container->getParameter('userStatusEn'));
    			$condition['flag'] = array_search('not-delete', $this->container->getParameter('flagEn'));
    			$applyByInfo = $em->getRepository('AcmeUserBundle:CmUser')->findUserByConditionJoined($condition);
    			
    			if (!$applyByInfo) {
    				throw $this->createNotFoundException('No teacher found for id');
    			}
    			
    			$contest->setName($form_data['name']);
    			$contest->setContestTypeInfo($contestTypeInfo);
    			$contest->setApplyByInfo($applyByInfo);
    			
    			$em->persist($contest);
    			$em->flush();
    			
    			$this->get('mail_manager')->contestCreate($contest);
    			return new Response('success');
    		}
    	}
    	throw $this->createNotFoundException();
    }
    
    /**
     * @Route("/delete", name="AcmeContestBundle_ContestDelete")
     * TODO
     */
    public function deleteAction() {
    	$request = $this->get('request');
    	if ($request->isXmlHttpRequest()) {
    		$condition['id'] = $request->get('id');
    
    		if ($this->get('security.context')->isGranted('ROLE_UNIVERSITY_ADMIN')) {
    			$condition['university'] =
    			$this->get('security.context')->getToken()
    			->getUser()->getUserInfo()->getUniversity();
    		}
    
    		$em = $this->getDoctrine()->getEntityManager();
    		$user = $em->getRepository('AcmeUserBundle:CmUser')->findUserByConditionJoined($condition);
    
    		if (!$user) {
    			throw $this->createNotFoundException('No user found for id ' . $condition['id']);
    		}
    
    		$user->setFlag(array_search('is-delete', $this->container->getParameter('flagEn')));
    		if ($user->getUserInfo()) {
    			$user->getUserInfo()->setFlag(array_search('is-delete', $this->container->getParameter('flagEn')));
    		}
    		$em->flush();
    		return new Response('success');
    	}
    	throw $this->createNotFoundException();
    }
    
    /**
     * @Route("/undelete", name="AcmeContestBundle_ContestUndelete")
     * TODO
     */
    public function undeleteAction() {
    	$request = $this->get('request');
    	if ($request->isXmlHttpRequest()) {
    		$condition['id'] = $request->get('id');
    
    		if ($this->get('security.context')->isGranted('ROLE_UNIVERSITY_ADMIN')) {
    			$condition['university'] =
    			$this->get('security.context')->getToken()
    			->getUser()->getUserInfo()->getUniversity();
    		}
    
    		$em = $this->getDoctrine()->getEntityManager();
    		$user = $em->getRepository('AcmeUserBundle:CmUser')->findUserByConditionJoined($condition);
    
    		if (!$user) {
    			throw $this->createNotFoundException('No user found for id ' . $condition['id']);
    		}
    
    		$user->setFlag(array_search('not-delete', $this->container->getParameter('flagEn')));
    		if ($user->getUserInfo()) {
    			$user->getUserInfo()->setFlag(array_search('not-delete', $this->container->getParameter('flagEn')));
    		}
    		$em->flush();
    		return new Response('success');
    	}
    	throw $this->createNotFoundException();
    }
}
